import ResManager from '../manager/ResManager';
import EventManager from '../manager/EventManager';
// import { UI_CONFIG } from '../game/AssetsConfig';
import UIManager, { UIConfig } from '../manager/UIManager';

import { _decorator, Asset, Component, Node, Sprite, Tween, Vec3 } from 'cc';
import { UI_CONFIG } from '../../game/AssetsConfig';
const { ccclass, property } = _decorator;
const tweenTag = 99;
@ccclass('BaseUI')
export default class BaseUI extends Component {
  protected onLoad(): void {
    this.showAnimation();
  }

  protected onDestroy(): void {
    this.unscheduleAllCallbacks();
    EventManager.Ins.offCaller(this);
    this.release(this.paths);
  }

  protected showAnimation() {
    let scaleNode = this.node.getChildByName('scaleNode');
    if (scaleNode) {
      scaleNode.scaleEx = 0;
      new Tween(scaleNode)
        .to(0.1, { scaleEx: 1.3 })
        .to(0.1, { scaleEx: 1 })
        .call(() => this.animFinish())
        .start();
    }
  }

  animFinish() {}

  initData(...args) {}

  protected paths = [];
  protected load<T extends Asset>(path: string, T: typeof Asset = Asset, onComplete?: Function) {
    this.paths.push(path);
    return ResManager.Ins.load<T>(path, T, onComplete);
  }

  /** 加载远程资源 */
  protected loadRemote<T extends Asset>(path: string, type: typeof Asset = Asset, onComplete?: Function) {
    this.paths.push(path);
    return ResManager.Ins.loadRemote<T>(path, type, onComplete);
  }
  /** 释放资源 */
  protected release(...paths) {
    for (const path of paths) {
      ResManager.Ins.release(path);
    }
  }

  protected on(eventName: string, callback: Function) {
    EventManager.Ins.on(eventName, callback, this);
  }

  protected off(eventName: string, callback: Function) {
    EventManager.Ins.off(eventName, callback, this);
  }

  protected emit(eventName: string, ...args) {
    EventManager.Ins.emit(eventName, ...args);
  }

  protected async open(ui: UIConfig, ...args) {
    await UIManager.Ins.open(ui, ...args);
  }

  protected close(ui?: UIConfig) {
    if (ui) {
      UIManager.Ins.close(ui, false, this.node);
      return;
    }
    let name = this.node.name;
    let pattern = /[A-Z][a-z]+/g;
    let key = '';
    let matches = pattern.exec(name);
    while (matches) {
      let match = matches[0].toLocaleUpperCase();
      key += key == '' ? match : `_${match}`;
      matches = pattern.exec(name);
    }
    let nums = '';
    if (name.search(/[0-9]/g) != -1) {
      nums = name.match(/\d+(\.\d+)?/g)[0];
    }
    if (nums != '') key += `_${nums}`;
    UIManager.Ins.close(UI_CONFIG[key], false, this.node);
    // UIManager.close(this.node)
  }

  protected get TweenTag() {
    return tweenTag;
  }
  protected DoTweenAddTag(twe: Tween<Node> | Tween<Sprite>) {
    twe.tag(tweenTag).start();
  }
}
